package com.gpframework.module.controller.system;

import com.gpframework.common.annotation.Log;
import com.gpframework.common.config.GpframeworkConfig;
import com.gpframework.common.constant.CacheConstants;
import com.gpframework.common.constant.Constants;
import com.gpframework.common.core.controller.BaseController;
import com.gpframework.common.core.domain.AjaxResult;
import com.gpframework.common.core.domain.entity.SysUser;
import com.gpframework.common.core.redis.RedisCache;
import com.gpframework.common.enums.BusinessType;
import com.gpframework.common.utils.ServletUtils;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.common.utils.ThreeDES2Utils;
import com.gpframework.common.utils.file.FileUploadUtils;
import com.gpframework.framework.config.ServerConfig;
import com.gpframework.module.common.domain.CommonWxUser;
import com.gpframework.module.common.domain.req.CommonWxUserReq;
import com.gpframework.module.common.service.ICommonWxUserService;
import com.gpframework.module.core.LoginUser;
import com.gpframework.module.pay.utils.joinpay.sdk.utitls.StringUtil;
import com.gpframework.module.service.TokenService;
import com.gpframework.module.service.system.ISysUserService;
import com.gpframework.module.sys.domain.req.LoginReq;
import com.gpframework.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 个人信息 业务处理
 *
 * @Author gpframework
 */
@RestController
@SuppressWarnings({"rawtypes"})
@RequestMapping("/system/user/profile")
public class SysProfileController extends BaseController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ICommonWxUserService commonWxUserService;

    /**
     * 个人信息
     */
    @GetMapping
    public Map profile() {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("msg", "操作成功");
        result.put("data", user);
        result.put("roleGroup", userService.selectUserRoleGroup(loginUser.getUsername()));
        result.put("postGroup", userService.selectUserPostGroup(loginUser.getUsername()));
        return result;
    }

    /**
     * 修改用户
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult updateProfile(@RequestBody SysUser user) {
        if (userService.updateUserProfile(user) > 0) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            // 更新缓存用户信息
            loginUser.getUser().setNickName(user.getNickName());
            loginUser.getUser().setPhonenumber(user.getPhonenumber());
            loginUser.getUser().setEmail(user.getEmail());
            loginUser.getUser().setSex(user.getSex());
            tokenService.setLoginUser(loginUser);
            if (StringUtil.isNotEmpty(loginUser.getUser())) {
                SysUser sysUser = loginUser.getUser();
                CommonWxUserReq commonWxUserReq = new CommonWxUserReq();
                commonWxUserReq.setBrandId(sysUser.getBrandId());
                commonWxUserReq.setBrandUserId(sysUser.getBrandUserId());
                CommonWxUser commonWxUser = commonWxUserService.findByBrandUserId(commonWxUserReq);
                if (StringUtil.isNotEmpty(commonWxUser)) {
                    commonWxUser.setNickname(user.getNickName());
                    commonWxUser.setUserName(user.getNickName());
                    commonWxUserService.updateById(commonWxUser);
                }
            }
            return AjaxResult.success();
        }
        return AjaxResult.error("修改个人信息异常，请联系管理员");
    }

    /**
     * 忘记密码
     *
     * @param loginReq
     * @return
     */
    @Log(title = "忘记密码", businessType = BusinessType.UPDATE)
    @PutMapping("/forgetPwd")
    public AjaxResult forgetPwd(@RequestBody LoginReq loginReq) {
        // 通过userName获取用户信息
        SysUser loginUser = userService.getUserByUserName(loginReq.getUserName());
        if (StringUtils.isNull(loginUser)) {
            return AjaxResult.error("用户不存在！");
        }
        // 从缓存中获取短信验证码
        String key = CacheConstants.EMPLOYEE_UPDATE_PASSWORD + Constants.MOBILE_AREA_CODE_CHINA + loginUser.getPhonenumber();
        Object smsCodeKey = redisCache.getCacheObject(key);
        if (StringUtils.isNull(smsCodeKey)) {
            return AjaxResult.error("短信验证码也过期,请重新发送！");
        }
        if (!loginReq.getSmsCode().equals(smsCodeKey.toString())) {
            return AjaxResult.error("验证码输入有误！");
        }
        logger.info("----------修改时密码：" + loginReq.getNewPassword() + "----------");
        if (userService.resetUserPwd(loginReq.getUserName(), SecurityUtils.encryptPassword(loginReq.getNewPassword()), ThreeDES2Utils.encode(loginReq.getNewPassword())) > 0) {
            String newPassword = loginReq.getNewPassword();
            // 更新缓存用户密码
            loginUser.setShowPassword(ThreeDES2Utils.encode(newPassword));
            loginUser.setPassword(SecurityUtils.encryptPassword(newPassword));
            // 清除缓存中的验证码
            redisCache.deleteObject(key);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 重置密码
     */
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePwd")
    public AjaxResult updatePwd(String oldPassword, String newPassword) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String userName = loginUser.getUsername();
        String password = loginUser.getPassword();
        if (!SecurityUtils.matchesPassword(oldPassword, password)) {
            return AjaxResult.error("修改密码失败，旧密码错误");
        }
        if (SecurityUtils.matchesPassword(newPassword, password)) {
            return AjaxResult.error("新密码不能与旧密码相同");
        }
        logger.info("----------修改时密码：" + newPassword + "----------");
        if (userService.resetUserPwd(userName, SecurityUtils.encryptPassword(newPassword), ThreeDES2Utils.encode(newPassword)) > 0) {
            // 更新缓存用户密码
            loginUser.getUser().setPassword(SecurityUtils.encryptPassword(newPassword));
            tokenService.setLoginUser(loginUser);
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常，请联系管理员");
    }

    /**
     * 头像上传
     */
    @Log(title = "用户头像", businessType = BusinessType.UPDATE)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            String avatar = FileUploadUtils.upload(GpframeworkConfig.getAvatarPath(), file);
            if (userService.updateUserAvatar(loginUser.getUsername(), GpframeworkConfig.getPrePath() + avatar)) {
                AjaxResult ajax = AjaxResult.success();
                ajax.setData(GpframeworkConfig.getPrePath() + avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }
}
